package com.csdig.cms.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.csdig.cms.dao.cache.ChannelCacheDAO;
import com.csdig.cms.model.Channel;

public class CacheUtils {

	public static String getChannelPath(Integer channelId) {
		StringBuffer result = new StringBuffer();
		ChannelCacheDAO channelCacheDao = BeanFactory.getBeanByType(ChannelCacheDAO.class);
		try {
			List<Channel> tempList = new ArrayList<Channel>();
			Channel channel = channelCacheDao.findByIdFromCache(channelId);
			while (channel != null && StringUtils.isNotEmpty(channel.getChannelPath())) {
				tempList.add(channel);
				if (channel.getParentId() == null || channel.getParentId() == Integer.valueOf(-1)) {
					channel = null;
				} else {
					channel = channelCacheDao.findByIdFromCache(channel.getParentId());
				}
			}
			for (int i = tempList.size() - 1; i >= 0; i--) {
				result.append(tempList.get(i).getChannelPath()).append("/");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result.toString();
	}

	public static List<Channel> getChannelNavList(Integer channelId) {
		if (channelId == null)
			return null;
		ChannelCacheDAO channelCacheDao = BeanFactory.getBeanByType(ChannelCacheDAO.class);
		List<Channel> result = new ArrayList<Channel>();
		try {
			Channel channel = channelCacheDao.findByIdFromCache(channelId);
			while (channel != null && channel.getParentId() != null && channel.getParentId() != Integer.valueOf(-1)) {
				result.add(channel);
				channel = channelCacheDao.findByIdFromCache(channel.getParentId());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}
}
